import logging
import random

import pyciv.attribute

def attack(attacker, defender):
    attackers = attacker.create_targets(False)
    defenders = defender.create_targets(True)

    try:
        attacker_losses = random.sample(attackers, 
                                        defender.attributes[pyciv.attribute.FIREPOWER])
    except ValueError:
        attacker_losses = attackers
    
    try:
        defender_losses = random.sample(defenders, 
                                        attacker.attributes[pyciv.attribute.FIREPOWER])
    except ValueError:
        defender_losses = defenders

    return (attacker_losses, defender_losses)

def estimate(attacker, defender, times=20):
    attacker_losses = []
    defender_losses = []
    for i in range(0, times):
        losses = attack(attacker, defender)
        attacker_losses.append(len(losses[0]) - losses[0].count(pyciv.attribute.EMPTY))
        defender_losses.append(len(losses[1]) - losses[1].count(pyciv.attribute.EMPTY))
    return (float(sum(attacker_losses)) / times, float(sum(defender_losses)) / times)

def handle_losses(unit, losses):
    for loss in losses:
        loss.handle_loss(unit)

class Result(object):
    def __init__(self, attacker = None, defender = None):
        self.empty = False
        if attacker and defender:
            self.attacker_description = str(attacker)
            self.defender_description = str(defender)
            self.attacker_losses = ""
            self.defender_losses = ""
        else:
            self.empty = True

    def losses(self, attacker, defender):
        self.attacker_losses += "".join(map(lambda item: str(item)[0], attacker))
        self.defender_losses += "".join(map(lambda item: str(item)[0], defender))

    def __str__(self):
        if not self.empty:
            result = "Combat result\n"
            result += "Att: %s\n" % self.attacker_description
            result += "Los: %s\n" % self.attacker_losses
            result += "Def: %s\n" % self.defender_description
            result += "Los: %s\n" % self.defender_losses
        else:
            result = "No result"
        return result
